import React, { useState, useEffect } from "react";

import './registrate_left.css'

import { Table, Button, Divider, Card, Modal, Avatar, message } from "antd";
import { UserOutlined } from '@ant-design/icons';
import PubSub from "pubsub-js";
import axios from "axios";

const { Meta } = Card


const columns = [
  {
    title: '缩略图',
    dataIndex: 'image_file',
    key: 'image_file',
    render: (url) => <img height={50} src={url}/>
  },
  {
    title: '患者姓名',
    dataIndex: 'p_name',
    key: 'p_name',
  },
  {
    title: '患者性别',
    dataIndex: 'p_sex',
    key: 'p_sex',
  },
  {
    title: '患者年龄',
    dataIndex: 'p_age',
    key: 'p_age',
  },
  {
    title: '拍摄时间',
    dataIndex: 'date',
    key: 'date',
  },
];

export default class Registrate_left extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      index: '',
      visible: false,
      modalTitle: '',
      fixedImage: '',
      movingImage: '',
      isUploadFixedImage: false,
      isUploadMovingImage: false,
    }
  }

  componentDidMount() {
    PubSub.subscribe('sendLeftImage', (name, record) => {
      this.setState({
        isUploadFixedImage: true,
        isUploadMovingImage: true,
        fixedImage: record.fixed_image.image_file,
        movingImage: record.moving_image.image_file,
      })
    })
  }

  handleOk = () => {
    if (this.state.modalTitle === '请选择参考图像') {
      this.setState({
        isUploadFixedImage: true,
        visible: false
      })
    } else if (this.state.modalTitle === '请选择浮动图像') {
      this.setState({
        isUploadMovingImage: true,
        visible: false
      })
    }
  };

  handleCancel = () => {
    this.setState({
      visible:false
    });
  };

  // 选择参考图像按钮
  chooseBeforeButton= () => {
    let data = { type: 'Fixed' }
    let url = '/registrationapi/queryregistrationimg'
    axios.post(url, data, {headers: {'Content-Type': 'application/json'}}
      ).then(res=>{
        if(res.status === 200 && res.data.code === 0){
          console.log(res.data.image_list)
          this.setState({
            data: res.data.image_list,
            visible: true,
            modalTitle: '请选择参考图像'
          })
        } else{
          console.log(res.data.msg)
          message.error(res.data.msg)
        }
    })
  };

  // 选择浮动图像按钮
  chooseAfterButton = () => {
    let data = { type: 'Moving' }
    let url = '/registrationapi/queryregistrationimg'
    axios.post(url, data, {headers: {'Content-Type': 'application/json'}}
      ).then(res=>{
        if(res.status === 200 && res.data.code === 0){
          console.log(res.data.image_list)
          this.setState({
            data: res.data.image_list,
            visible: true,
            modalTitle: '请选择浮动图像'
          })
        } else{
          console.log(res.data.msg)
          message.error(res.data.msg)
        }
    })
  };

  // 设置行的类函数
  rowClassNameFun = (record, index) => {
    if (index === this.state.index)
      return 'mySelfClassName'
  }

  // 更新行函数
  updateRow = (record, index) => {
    if (this.state.modalTitle === '请选择参考图像') {
      this.setState({
        index: index,
        fixedImage: record.image_file,
      })
      const flag = false;
      PubSub.publish("sendFlagParam", flag);
    } else if (this.state.modalTitle === '请选择浮动图像') {
      this.setState({
        index: index,
        movingImage: record.image_file,
      })
      const flag = true;
      PubSub.publish("sendFlagParam", flag);
    }
    // 发送给兄弟组件图片的地址
    PubSub.publish("sendRegistrationParam", record);
  }

  // 选中参考图像卡片函数
  chooseFixedImageCard = () => {
    // 发送给兄弟组件图片的地址
    const flag = false;
    PubSub.publish("sendFlagParam", flag);
  }

  // 选中浮动图像卡片函数
  chooseMovingImageCard = () => {
    // 发送给兄弟组件图片的地址
    const flag = true;
    PubSub.publish("sendFlagParam", flag);
  }


  // 点击配准按钮函数
  goToRegistration = () => {
    if (this.state.fixedImage === '' || this.state.movingImage === '') {
      message.error('请选择参考图像或浮动图像')
    } else {
      message.loading({ content: '配准中...', duration: 0 })
      let data = {
        fixedImage: this.state.fixedImage,
        short_fixedImage: this.state.fixedImage.replace(/^data:image\/\w+;base64,/, ""),
        movingImage: this.state.movingImage,
        short_movingImage: this.state.movingImage.replace(/^data:image\/\w+;base64,/, "")
      }
      let url = '/registrationapi/registration'
      axios.post(url, data, {headers: {'Content-Type': 'application/json'}}
        ).then(res=>{
          if(res.status === 200 && res.data.code === 0){
            message.destroy();
            message.success({ content: '配准成功！', duration: 2 })
            PubSub.publish("sendHomeImage", res.data.registration_image.original_image);
            PubSub.publish("sendRightImage", res.data.registration_image);
          } else{
            console.log(res.data.msg)
            message.error(res.data.msg)
          }
      })
    }
  }


  render() {
    return (
      <div className="registrate_left">
        <Modal
          width={590}
          title={this.state.modalTitle}
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          footer={[
            <Button key="back" onClick={this.handleCancel}>取消</Button>,
            <Button key="submit" type="primary" onClick={this.handleOk}>确定</Button>,
          ]}
        >
          <Table
            columns={columns}
            dataSource={this.state.data}
            pagination={false}
            scroll={{ y:400 }}
            showHeader={true}
            rowClassName={this.rowClassNameFun}
            onRow={ (record, index) => {
              return {
                onClick: event => { this.updateRow(record, index) }, // 点击行
              };
            }}
          />
        </Modal>
        <div className="top">
          <Card
            hoverable
            onClick={this.chooseFixedImageCard}
            style={{ width: 240 }}
            cover={this.state.isUploadFixedImage === false ?
              <Avatar shape="square" size={240} icon={<UserOutlined />} /> :
              <img src={this.state.fixedImage} />}
          >
            <Meta title="参考图像(时间点在前)" description="只有已经定点和绘制轮廓后的图像可供选择" />
          </Card>
          <Button type="primary" className="registrate_button" onClick={this.chooseBeforeButton}>选择图片</Button>
        </div>
        <Divider style={{ width:'100%', margin:'0' }} />
        <div className="bottom">
          <Card
            hoverable
            onClick={this.chooseMovingImageCard}
            style={{ width: 240 }}
            cover={this.state.isUploadMovingImage === false ?
              <Avatar shape="square" size={240} icon={<UserOutlined />} /> :
              <img src={this.state.movingImage} />}
          >
            <Meta title="浮动图像(时间点在后)" description="只有已经定点和绘制轮廓后的图像可供选择" />
          </Card>
          <Button type="primary" className="registrate_button" onClick={this.chooseAfterButton}>选择图片</Button>
        </div>
        <Button type="primary" block size="large" style={{ marginTop: 15 }} onClick={this.goToRegistration}>配准</Button>
      </div>
    )
  }
}